<?php

namespace App\Http\Controllers\Article;

use App\Http\Controllers\BaseController;
use App\Models\ArticleCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TopicCategoryController extends BaseController
{
    public function index(Request $request)
    {
        $param = $this->validate($request,[
            'user_id' => 'integer'
        ]);

        $query =  ArticleCategory::query()
            ->selectRaw('*,(select sum(view_count) from article_browses where article_id in
            (select id from articles where category_id=article_categories.id)) as view_count')
            ->where('status',1)
            ->where('type',1)
            ->withCount(['article' => function($q){
                $q->where('type',5);
            }]);

        if (isset($param['user_id']) && $param['user_id'] !==''){
            $query->where('user_id',$param['user_id']);
        }

        $data = $query->orderBy('sort')
            ->orderByDesc('id')
            ->get();

        return $this->success($data);
    }


    public function store(Request $request)
    {
        $param = $this->validate($request,[
            'name' => 'required',
            'image' => 'required',
            'intro' => 'required|max:500'
        ]);


        $topic_category_id =  DB::table('article_categories')->insertGetId([
            'sort' => 0,
            'name' => $param['name'],
            'image' => $param['image'],
            'intro' => $param['intro'],
            'user_id' => auth('api')->id(),
            'status' => 1,
            'type' => 1,
            'parent_id' => 0,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);

        return $topic_category_id ? $this->success(['topic_category_id' => $topic_category_id]) : $this->error();
    }


    public function show(Request $request)
    {
        $params = $this->validate($request,[
            'category_id' =>  'required|integer'
        ]);

        $category = DB::table('article_categories')
            ->selectRaw('*,(select sum(view_count) from article_browses where article_id in
            (select id from articles where category_id=article_categories.id)) as view_count')
            ->where('id',$params['category_id'])
            ->first();


        return $this->success($category);
    }
}
